#!/usr/bin/env node

/**
 * Simple Configuration Script
 *
 * 轻量级本地MCP工具配置脚本
 * 提供交互式命令行界面配置API密钥
 */

const readline = require('readline');
const fs = require('fs');
const path = require('path');

class SimpleConfigurator {
    constructor(projectRoot) {
        this.projectRoot = projectRoot || process.cwd();
        this.rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout
        });
        this.config = this.loadExistingConfig();
    }

    /**
     * 加载现有配置
     */
    loadExistingConfig() {
        const config = {
            currentProviderModel: '',
            moonshot: { apiKey: '', baseUrl: 'https://api.moonshot.cn/v1' },
            tencent: { apiKey: '', baseUrl: 'https://api.hunyuan.cloud.tencent.com/v1' },
            zai: { apiKey: '', baseUrl: 'https://open.bigmodel.cn/api/paas/v4' },
            custom: { name: '', apiKey: '', baseUrl: '' }
        };

        try {
            // 使用JSON配置管理器读取配置
            const JsonConfigManager = require('./lib/config/json-config-manager');
            const ConfigPathResolver = require('./lib/config/config-path-resolver');

            const pathResolver = new ConfigPathResolver();
            const configManager = new JsonConfigManager(this.projectRoot);

            const configPathInfo = pathResolver.getBestConfigPath(this.projectRoot);
            if (configPathInfo) {
                configManager.configPath = configPathInfo.path;
                const jsonConfig = configManager.loadConfig();

                // 转换JSON配置为命令行界面需要的格式
                config.currentProviderModel = jsonConfig.current_provider_model || '';

                if (jsonConfig.providers) {
                    for (const [providerName, providerConfig] of Object.entries(jsonConfig.providers)) {
                        if (config[providerName]) {
                            config[providerName].apiKey = providerConfig.api_key || '';
                            config[providerName].baseUrl = providerConfig.base || '';
                        }
                    }
                }
            }
        } catch (error) {
            console.log('⚠️  读取现有配置失败，使用默认配置');
        }

        return config;
    }

    /**
     * 保存配置到文件
     */
    saveConfig() {
        try {
            // 转换为JSON配置格式
            const jsonConfig = {
                current_provider_model: this.config.currentProviderModel,
                providers: {}
            };

            // 只配置有API密钥的提供商
            const providers = ['moonshot', 'tencent', 'zai', 'custom'];
            for (const provider of providers) {
                if (this.config[provider].apiKey) {
                    jsonConfig.providers[provider] = {
                        api_key: this.config[provider].apiKey,
                        base: this.config[provider].baseUrl
                    };
                }
            }

            // 使用JSON配置管理器保存
            const JsonConfigManager = require('./lib/config/json-config-manager');
            const ConfigPathResolver = require('./lib/config/config-path-resolver');

            const pathResolver = new ConfigPathResolver();
            const configManager = new JsonConfigManager(this.projectRoot);

            const configPathInfo = pathResolver.getBestConfigPath(this.projectRoot);
            if (configPathInfo) {
                configManager.configPath = configPathInfo.path;
                configManager.saveConfig(jsonConfig);
                return true;
            } else {
                console.error('❌ 无法确定配置文件路径');
                return false;
            }
        } catch (error) {
            console.error('❌ 保存配置失败:', error.message);
            return false;
        }
    }

    /**
     * 询问用户输入
     */
    ask(question) {
        return new Promise((resolve) => {
            this.rl.question(question, (answer) => {
                resolve(answer.trim());
            });
        });
    }

    /**
     * 显示配置菜单
     */
    showMenu() {
        console.log('\n🔧 Vision Analyzer 配置管理');
        console.log('========================');
        console.log('1. 配置提供商');
        console.log('2. 查看当前配置');
        console.log('3. 保存并退出');
        console.log('4. 退出不保存');
        console.log('========================');
    }

    /**
     * 显示当前配置
     */
    showCurrentConfig() {
        console.log('\n📋 当前配置:');
        console.log('------------------');

        if (this.config.currentProviderModel) {
            console.log(`当前模型: ${this.config.currentProviderModel}`);
        }

        const providers = ['moonshot', 'tencent', 'zai', 'custom'];
        let hasConfig = false;

        for (const provider of providers) {
            if (this.config[provider].apiKey) {
                console.log(`${provider.toUpperCase()}: ✓ 已配置`);
                hasConfig = true;
            }
        }

        if (!hasConfig) {
            console.log('未配置任何提供商');
        }
        console.log('------------------');
    }

    /**
     * 配置提供商
     */
    async configureProvider() {
        console.log('\n🤖 选择要配置的提供商:');
        console.log('1. Moonshot (月之暗面)');
        console.log('2. Tencent (腾讯混元)');
        console.log('3. Zhipu AI (智谱AI)');
        console.log('4. 自定义');
        console.log('0. 返回主菜单');

        const choice = await this.ask('请选择 (0-4): ');

        switch (choice) {
            case '1':
                await this.configureProviderDetails('moonshot', 'Moonshot (月之暗面)');
                break;
            case '2':
                await this.configureProviderDetails('tencent', 'Tencent (腾讯混元)');
                break;
            case '3':
                await this.configureProviderDetails('zai', 'Zhipu AI (智谱AI)');
                break;
            case '4':
                await this.configureProviderDetails('custom', '自定义提供商');
                break;
            case '0':
                return;
            default:
                console.log('❌ 无效选择');
        }
    }

    /**
     * 配置具体提供商详情
     */
    async configureProviderDetails(providerKey, providerName) {
        console.log(`\n🔧 配置 ${providerName}`);
        console.log('==================');

        // API密钥
        const apiKey = await this.ask('请输入API密钥 (留空跳过): ');
        if (!apiKey) {
            console.log('⚠️  跳过配置');
            return;
        }

        this.config[providerKey].apiKey = apiKey;

        // Base URL (仅自定义提供商)
        if (providerKey === 'custom') {
            const name = await this.ask('请输入提供商名称: ');
            if (name) {
                this.config.custom.name = name;
            }

            const baseUrl = await this.ask('请输入Base URL (可选): ');
            if (baseUrl) {
                this.config.custom.baseUrl = baseUrl;
            }
        }

        // 设置为当前提供商
        this.config.currentProviderModel = `${providerKey}-gpt-4o`;

        console.log(`✅ ${providerName} 配置完成`);
    }

    /**
     * 运行配置器
     */
    async run() {
        console.log('🚀 Vision Analyzer 简单配置工具');
        console.log('==============================\n');

        while (true) {
            this.showMenu();
            const choice = await this.ask('\n请选择操作 (1-4): ');

            switch (choice) {
                case '1':
                    await this.configureProvider();
                    break;
                case '2':
                    this.showCurrentConfig();
                    break;
                case '3':
                    if (this.saveConfig()) {
                        console.log('\n✅ 配置已保存');
                        this.rl.close();
                        return;
                    } else {
                        console.log('\n❌ 配置保存失败');
                    }
                    break;
                case '4':
                    console.log('\n👋 配置未保存，退出');
                    this.rl.close();
                    return;
                default:
                    console.log('❌ 无效选择，请重试');
            }
        }
    }
}

// 主程序
if (require.main === module) {
    const projectRoot = process.argv[2] || process.cwd();
    const configurator = new SimpleConfigurator(projectRoot);
    configurator.run().catch(error => {
        console.error('❌ 配置工具出错:', error);
        process.exit(1);
    });
}

module.exports = SimpleConfigurator;